package com.example.orderservice.config;


import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.orderservice.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@RestControllerAdvice
public class globalExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e, HttpServletRequest request) {
        // 如果是文件下载请求，不返回 JSON
        if (isFileDownloadRequest(request)) {
            return null; // 返回 null，让 Spring Boot 继续处理原始响应
        }
        return Result.error("文件大小超出限制1.0MB");
    }
    // 2. 处理 Sentinel 流控/熔断降级异常
    @ExceptionHandler(BlockException.class)
    public Result handleSentinelBlockException(BlockException e, HttpServletRequest request) {
        if (isFileDownloadRequest(request)) return null;
        // 返回降级响应（可自定义降级逻辑）
        return Result.error("系统繁忙，请稍后再试 (Sentinel Fallback)");
    }
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request) {
        // 如果是文件下载请求，不返回 JSON
        if (isFileDownloadRequest(request)) {
            return null;
        }
        return Result.error(e.getMessage());
    }

    // 判断是否为文件下载请求（根据 Content-Type）
    private boolean isFileDownloadRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }
}
